package cn.ztuo.bitrade.service;

import cn.ztuo.bitrade.dao.CesspitDao;
import cn.ztuo.bitrade.dao.MemberWalletDao;
import cn.ztuo.bitrade.entity.Cesspit;
import cn.ztuo.bitrade.entity.MemberWallet;
import cn.ztuo.bitrade.entity.QCesspit;
import cn.ztuo.bitrade.service.Base.BaseService;
import cn.ztuo.bitrade.util.PredicateUtils;
import cn.ztuo.bitrade.vo.CesspitVO;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CesspitService extends BaseService {
    @Autowired
    private CesspitDao cesspitDao;
    @Autowired
    private MemberWalletDao memberWalletDao;

    public List<Cesspit> findAll() {
        return cesspitDao.findAll(new Sort(Sort.Direction.DESC,"id"));
    }

    public Cesspit findById(Long id) {
        return cesspitDao.findOne(id);
    }

    public Cesspit save(Cesspit cesspit) {
        return cesspitDao.save(cesspit);
    }

    public int subAmount(BigDecimal amount, MemberWallet wallet, Long userId) throws Exception{
        int is_success =  memberWalletDao.decreaseBalance(wallet.getId(),amount);
        if(is_success == 1){
            return is_success;
        }else{
            throw new Exception("账户资产不足：" + userId);
        }
    }

    public Page<Cesspit> getPage(CesspitVO cesspitVO){
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();
        if(StringUtils.isNotEmpty(cesspitVO.getCoin())) {
            booleanExpressions.add(QCesspit.cesspit.coin.eq(cesspitVO.getCoin()));
        }
        if(cesspitVO.getStatus()!=3){
            booleanExpressions.add(QCesspit.cesspit.status.eq(cesspitVO.getStatus()));
        }
        if(cesspitVO.getId()!=null){
            booleanExpressions.add(QCesspit.cesspit.id.eq(cesspitVO.getId()));
        }
        Predicate predicate = PredicateUtils.getPredicate(booleanExpressions);
        Sort sort = new Sort(Sort.Direction.ASC,"status");
        Pageable pageable = new PageRequest(cesspitVO.getPageNum()-1,cesspitVO.getPageSize(),sort);
        return cesspitDao.findAll(predicate,pageable);
    }

    public List<Cesspit> findRun(Long status){
        return cesspitDao.findByStatus(status);
    }

    /**
     * 获取质押数量大于当前NUmber的记录
     * @param number
     * @return
     */
    public List<Cesspit> selectGtMin(Long number){
        return cesspitDao.selectGtMin(number);
    }


}
